package com.aso114.project.exam;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.adapter.AnswerCardAdapter;
import com.aso114.project.base.BaseSimpleActivity;
import com.aso114.project.bean.QuestionBaseBean;
import com.aso114.project.bean.QuestionBean;
import com.aso114.project.commonview.MyGridView;
import com.aso114.project.commonview.NoticeDialog;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.Constant;
import com.aso114.project.util.Helper;
import com.aso114.project.util.SystemBarHelper;
import com.aso114.project.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 答题卡
 */
public class AnswerCardActivity extends BaseSimpleActivity {
    //图片编号
    @BindView(R.id.layout_title_bar_back_iv)
    ImageView layoutTitleBarBackIv;
    @BindView(R.id.layout_title_bar_title_tv)
    TextView layoutTitleBarTitleTv;


    Intent intent;
    AnswerCardAdapter adapter;
    @BindView(R.id.gridview)
    MyGridView gridview;
    QuestionBean mdata;
    public static boolean issubmitpaper = false;
    public static AnswerCardActivity instance;
    @BindView(R.id.papertitle)
    TextView papertitle;
    @BindView(R.id.submit)
    LinearLayout submit;
    Dialog dialog;
    @BindView(R.id.title_top_ly)
    RelativeLayout titleTopLy;
    private ArrayList<QuestionBaseBean> baseBean;

    @Override
    protected int getResouseId() {

        return R.layout.answercard;
    }

    @Override
    protected void initView() {
        SystemBarHelper.immersiveStatusBar(this);
        SystemBarHelper.setHeightAndPadding(this, titleTopLy);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SystemBarHelper.immersiveStatusBar(this, 0);
            SystemBarHelper.setStatusBarDarkMode(this);
        }
        instance = this;
        layoutTitleBarTitleTv.setText("答题卡");
//        baseBean = (ArrayList<QuestionBaseBean>) getIntent().getSerializableExtra("QuestionBaseBean");
//        baseBean = QuestionTestActivity.baseBean;

        if (Constant.title_tv.equals("7") || Constant.title_tv.equals("8")) {
            submit.setVisibility(View.GONE);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(ArrayList<QuestionBaseBean> event) {
        baseBean = event;

        if (baseBean != null) {
            papertitle.setText(baseBean.get(0).getRealPaperTitle());
        }

        adapter = new AnswerCardAdapter(this, baseBean);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                QuestionTestActivity.viewPager.setCurrentItem(position, false);
                finish();
            }
        });
    }


    @Override
    protected void initData() {


    }

    @Override
    protected void getBroadcast(Context context, Intent intent) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.layout_title_bar_back_iv, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_title_bar_back_iv:
                finish();
                break;
            case R.id.submit:
                //计算已经做了多少题
                int rightAnswer = 0;
                for (QuestionBaseBean r : baseBean
                        ) {
                    if (r.isFinishAnswer())
                        rightAnswer++;

                }


                //还剩多少题没做
                int finishanswer = baseBean.size() - rightAnswer;
                new NoticeDialog(AnswerCardActivity.this, "还有" + finishanswer + "题未做完,确定交卷吗?",
                        "", "确定", new NoticeDialog.NoticeOnClick() {
                    @Override
                    public void onclick() {


                        final View dialogview = AnswerCardActivity.this.getLayoutInflater().inflate(
                                R.layout.loading_view, null);
                        dialog = new Dialog(AnswerCardActivity.this, R.style.dialogStyle);
                        dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        dialog.getWindow().setGravity(Gravity.CENTER);
                        // 设置点击外围解散
                        dialog.setCanceledOnTouchOutside(true);
                        dialog.setCancelable(true);//设置是否可以按退回键取消
                        dialog.show();
                        TextView tv = (TextView) dialogview.findViewById(R.id.wecate);
                        tv.setText("正在提交试卷,请稍后...");

                        JSONObject dataobj = new JSONObject();
                        final JSONArray idCradArray = new JSONArray();

                        int i = baseBean.size();
                        try {
                            //提交试卷 不需要做已经答题的判断
                            for (int j = 0; j < i; j++) {

                                JSONObject stoneObject = new JSONObject();
                                stoneObject.put("PaperId", baseBean.get(j)
                                        .getPaperId());
                                stoneObject.put("QuestionId", baseBean.get(j)
                                        .getQuestionId());
                                if (baseBean.get(j).isChooseResult() == true) {
                                    stoneObject.put("QuestionState", "1");// 答题对与错  1 对 2 错
                                } else {
                                    stoneObject.put("QuestionState", "2");// 答题对与错  1 对 2 错
                                }


                                if (!baseBean.get(j).isFinishAnswer()) {//判断该题是否已经作答

                                    JSONArray Array = new JSONArray();
//                                    Array.put("");
                                    stoneObject.put("UserAnswer", Array);//数组

                                    //没有作答 赋值时间都为0
                                    stoneObject.put("AnswerDuration", "0");//答题时间
                                } else {//已经作答

                                    stoneObject.put("AnswerDuration", String.valueOf(baseBean.get(j).getQuestiontime()));//答题时间
                                    System.out.println("答题时间===" + baseBean.get(j).getQuestiontime() + "==第几题" + j);
                                    if (baseBean.get(j).isChooseResult()) {//判断选择的结果是否正确
                                        System.out.println("答案是答对的答案===" + baseBean.get(j).getRightAnswer() + "==第几题" + j);

                                        JSONArray Array = new JSONArray();
                                        if ("10".equals(baseBean.get(j).getQuestionTypeId()) || "35".equals(baseBean.get(j).getQuestionTypeId())) {
                                            for (int r = 0; r < baseBean.get(j).getRightList().size(); r++) {
                                                Array.put(Helper.asciiToString(baseBean.get(j).getRightList().get(r)));
                                            }
                                        } else {
                                            Array.put(Helper.asciiToString(baseBean.get(j).getRightAnswer()));
                                        }

                                        stoneObject.put("UserAnswer", Array);//数组

                                    } else {
                                        JSONArray Array = new JSONArray();
                                        if ("10".equals(baseBean.get(j).getQuestionTypeId()) || "35".equals(baseBean.get(j).getQuestionTypeId())) {
                                            for (int r = 0; r < baseBean.get(j).getResultList().size(); r++) {
                                                Array.put(Helper.asciiToString(baseBean.get(j).getResultList().get(r)));
                                            }
                                        } else {
                                            Array.put(Helper.asciiToString(baseBean.get(j).getErrorAnswer()));
                                        }
                                        stoneObject.put("UserAnswer", Array);//数组
                                        System.out.println("答案是答错的答案===" + baseBean
                                                .get(j).getErrorAnswer() + "==第几题" + j);
                                    }
                                }

                                stoneObject.put("QuestionScore", baseBean.get(j)
                                        .getQuestionScore());

                                idCradArray.put(stoneObject);

                            }

                            System.out.println("----->A----" + idCradArray.toString() + "----->");
                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }

                        float score = 0;
                        for (QuestionBaseBean r : baseBean) {
                            if (r.isChooseResult()) {
                                score += Float.valueOf(r.getQuestionScore());

                                System.out.println("本题分数====" + r.getQuestionScore());
                            }


                        }
                        System.out.println("总分数====" + score);

                        CommentModel.getInstant().post_paper(baseBean.get(0)
                                .getPaperId(), "1", String.valueOf(score), idCradArray.toString(), new CallBack() {
                            @Override
                            public void onSuccess(Object o, boolean isSuccess, String msg) {
                                dialog.cancel();
                                Helper.gotoLogin(isSuccess);//token失效去重新登陆

                                issubmitpaper = true;//确定提交交卷
                                EventBus.getDefault().postSticky(baseBean);
                                intent = new Intent(AnswerCardActivity.this,
                                        PracticeReportActivity.class);
                                startActivity(intent);

                            }

                            @Override
                            public void onFailure(String fail) {
                                dialog.cancel();
                                ToastUtils.showToast(AnswerCardActivity.this, "提交试卷失败,请重新提交");

                            }
                        });


                    }
                }).show();


                break;

        }
    }


}
